<template>
  <div class="loginBox">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="login">
      <h3>叩丁狼商品管理系统</h3>
      <el-form-item prop="username" label-width="auto">
        <el-input v-model="ruleForm.username" autocomplete="off" placeholder="请输入账号">
          <template #prefix>
            <el-icon :size="24">
              <Avatar />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password" label-width="auto">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" placeholder="请输入密码">
          <template #prefix>
            <el-icon :size="24">
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-button type="primary" size="large" @click="submitForm(ruleFormRef)">登录</el-button>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { FormInstance, ElMessage } from 'element-plus'
import { Avatar, Lock } from '@element-plus/icons-vue'
import { loginAPI } from "./api"
import { useRouter } from "vue-router"
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}
const ruleForm = reactive({
  username: "",
  password: "",
})
const rules = reactive({
  username: [{ required: true, message: "请输入账号", trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loginAPI(ruleForm).then((res) => {
        if (res.code === 200) {
          localStorage.setItem("token", res.data.tokenHead + res.data.token)
          ElMessage.success("登录成功")
          router.push("/index")
        }
      })
    } else {
      ElMessage.error('请输入账号或密码')
    }
  })
}
</script>

<style scoped lang="less">
.loginBox {
  height: 100%;
  background-color: #2D3A4B;
  position: relative;

  .login {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 418px;
    margin: auto;

    h3 {
      font-size: 24px;
      color: #fff;
      text-align: center;
      height: 50px;
      line-height: 50px;
    }

    :deep(.el-input__wrapper) {
      width: 100%;
      background-color: #283443;
    }

    :deep(.el-input__inner) {
      height: 50px;
      color: #fff;
    }

    :deep(.el-button) {
      width: 100%;
    }
  }
}
</style>
